const positionTest = require('../views/position.art')
const positionMovieList = require('../views/movie-list.art')
const positionModel = require('../models/position')


const BScroll = require('better-scroll')

class Position {
    constructor(){
        this.list = [];
        this.movies = [];
        this.i = 2;
        this.j;
    }

    renderer(list){
        this.arr = [];
        for(let i = 0;i<list.length;i++){
           this.arr.push(list[i].img.replace('w.h','128.180'));
        }
        let movieList = positionMovieList({
            list,
            arr:this.arr
        })

        $('main ul').html(movieList)
    }

    async render(){
        let that = this

        let result = await positionModel.get1()  //得到电影数据
        let positionHtml = positionTest({});

        

        let $main = $('main');
        $main.html(positionHtml);
        $('.city').html(localStorage.getItem('cityHistory') || '北京');


        $('.city').on('tap',function(){  //城市路由点击
            location.hash = 'city'
        })

        $('#search').on('tap',function(){
            location.hash = 'search'
        })


        let list = this.list = result.movieList
        this.renderer(list)
        let movies = this.movies = result.movieIds
        let $imgFoot = $('.foot img');

        let bScroll = new BScroll.default($main.get(0),{
            probeType:2
        })

        bScroll.on('scrollEnd',async function(){
            //上拉加载更多
            if(this.maxScrollY >= this.y){
                $imgFoot.attr('src','/assets/images/ajax-loader.gif');
                let str = '';
                that.i += 10
                that.j = that.i+10
                for(that.i; that.i<=that.j; that.i++){
                    str += movies[that.i]+'%2C';
                }
                let nnn=str.slice(0,-3);
                let result = await positionModel.get2({
                    movieIds:nnn
                })

                let list = this.list = result.coming
                that.list = [...that.list, ...list]
                that.renderer(that.list)

                bScroll.scrollBy(0, 40)
            }

        })

        bScroll.on('scroll',function(){
            if(this.maxScrollY > this.y){
              $imgFoot.addClass('down');
            }
        })
    }
}

export default new Position();